package com.wg.handler;

import com.wg.R;
import com.wg.enums.HttpCodeEnum;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
public class WgExceptionHandler {

    @ExceptionHandler(WgException.class)
    public R blogSystemExceptionHandler(WgException e) {
        return R.fail(e.getCode(), e.getMsg());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R argsValidExceptionHandler(MethodArgumentNotValidException ex){
        List<FieldError> fieldErrors = ex.getBindingResult().getFieldErrors();
        StringBuffer sb = new StringBuffer();
        for (FieldError fi : fieldErrors) {
            sb.append(fi.getDefaultMessage()+" ");
        }
        return R.fail(400, sb.toString());
    }

    @ExceptionHandler(Exception.class)
    public R exceptionHandler(Exception e) {
        return R.fail(HttpCodeEnum.SYSTEM_ERROR.getCode(), e.getMessage());
    }

}
